//
//  OAuthViewController.swift
//  JMWB
//
//  Created by 个人电脑 on 16/3/19.
//  Copyright © 2016年 个人电脑. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigationBar()
        loginPage()
    }

   

}
extension OAuthViewController{
//设置导航栏内容
   private func setupNavigationBar(){
    
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "colse")
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: "autoFill")
    title = "登陆界面"
    }
    
    private func loginPage(){
    //获取urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        //创建URL
        guard let url = NSURL(string: urlString) else{
        return
        }
        // 3.创建URLRequest对象
        let request = NSURLRequest(URL: url)
        // 4.加载request对象
        webView.loadRequest(request)
    }
}

extension OAuthViewController{

    @objc private func colse(){
    dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFill(){
        // 1.获取要执行的js(JavaScript)代码
        let jsCode = "document.getElementById('userId').value='peng827@qq.com';document.getElementById('passwd').value='900827chen';"
        
        // 2.webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
}
extension OAuthViewController: UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    // 加载某一个页面时会执行该方法
    // 返回值 : true : 继续加载该页面 false : 不会加载该页面
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //打印所以的URL
//        print(request.URL)
        // 1.获取URL对应的字符串
        guard let urlString = request.URL?.absoluteString else{
        return true
        }
        // 2.判断字符串中是否有code
        if !urlString.containsString("code="){
        return true
        }
        // 3.取出code
        guard let codeString = urlString.componentsSeparatedByString("code=").last else{
        return true
        }
         // 4.换取AccessToken
        UserAccountViewModel.shareIntance.loadAccessToken(codeString) { (isSuccess) -> () in
            if !isSuccess{
            return
            }
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                //显示欢迎界面
                UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
            })
        }
        return false
    }
    
}
